import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message, Button } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import request from '@/utils/request';
import { SelectForm } from '@/components/UserForm';
import styles from './index.less';

const { TextArea } = Input;
const ReEstimateActionModal = ({ form, visible, setVisible, onCancel, onOk, taskId, reEstimateUser }) => {
    const { getFieldDecorator } = form;
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [disabled, setDisabled] = useState(false);
    const [textArea, setTextArea] = useState('');
    const [taskRecord, setTaskRecord] = useState('');

    const getTaskRecord = async () => {
        if (taskId) {
            const result = await request(`/api/oa/v1/work/task/taskinfos/${taskId}/checktaskbeforeapply`, {
                method: 'GET'
            });
            if (result.code === 10000) {
                setTaskRecord(result.data);
            } else {
                message.error(result.msg);
            }
        }
    };

    const handleOk = () => {
        form.validateFields(async (err, values) => {
            if (err) return;
            setConfirmLoading(true);
            console.log(values, '============values');
            const { files, employeeListIds, ...rest } = values;

            const selectList = [];
            reEstimateUser.map(v => {
                employeeListIds.map(t => {
                    if (v.employeeCode === t) {
                        selectList.push(v);
                    }
                    return '';
                });
                return '';
            });

            const result = await request('/api/oa/v1/work/task/estimation/reestimateapply', {
                method: 'POST',
                data: {
                    ...rest,
                    resourceRelation: files ? [files.uploadResourceFile] : [],
                    taskId,
                    employeeList: selectList
                }
            });
            if (result.code === 10000) {
                message.success('提交成功');
                setVisible(false);
                form.resetFields();
                onOk();
            } else {
                message.error(result.msg);
            }
            setConfirmLoading(false);
        });
    };
    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };
    const formLayout = {
        wrapperCol: { span: 16 },
        labelCol: { span: 6 }
    };

    const handleTextAreaChange = e => {
        const { value } = e.target;
        setTextArea(value);
    };
    useEffect(() => {
        if (
            form.getFieldValue('files') &&
            form.getFieldValue('files').allFileList &&
            form.getFieldValue('files').allFileList.length >= 5
        ) {
            setDisabled(true);
        } else {
            setDisabled(false);
        }
    }, [form.getFieldValue('files')]);

    useEffect(() => {
        if (visible) {
            getTaskRecord();
        }
    }, [taskId, visible]);
    return (
        <Modal
            title="重估申请"
            width={864}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            onCancel={handleCancel}
        >
            <Form {...formLayout}>
                {taskRecord.auditEmployeeName && (
                    <Form.Item label="温馨提示">
                        确定后，需由审核人【{taskRecord.auditEmployeeName}】通过后方可生效
                    </Form.Item>
                )}
                {!taskRecord.auditEmployeeName && taskRecord.launchEmployeeName && (
                    <Form.Item label="温馨提示">
                        确定后，需由发起人【{taskRecord.launchEmployeeName}】通过后方可生效
                    </Form.Item>
                )}
                <Form.Item label="选择重估人员">
                    {getFieldDecorator('employeeListIds', {
                        rules: [
                            {
                                required: true,
                                message: '选择重估人员'
                            }
                        ]
                    })(
                        <SelectForm
                            getData={() => reEstimateUser}
                            fieldsName={{
                                selectValue: 'employeeCode',
                                selectTitle: 'employeeName'
                            }}
                            selectProps={{
                                placeholder: '请选择',
                                allowClear: true,
                                mode: 'multiple'
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="原因">
                    {getFieldDecorator('operateReason', {
                        rules: [
                            { min: 1, max: 500, message: '请输入1~500个字符' },
                            {
                                required: true,
                                message: '请输入原因'
                            },
                            {
                                pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                message: '此处不能输入空格'
                            }
                        ],
                        initialValue: null
                    })(<TextArea rows={5} maxLength={500} style={{ width: 500 }} onChange={handleTextAreaChange} />)}
                    <div style={{ lineHeight: 1, color: '#aaa' }}>
                        还可输入
                        <span style={{ color: 'red' }}>{500 - textArea.length < 1 ? 0 : 500 - textArea.length}</span>字
                    </div>
                </Form.Item>
                <Form.Item
                    label="附件"
                    extra={
                        <span style={{ wordBreak: 'break-all' }}>
                            （支持非运行文件格式，每个文件大小不超过50M，最多上传5个附件）
                        </span>
                    }
                >
                    {form.getFieldDecorator('files')(
                        <FileUpload
                            checkFileSize={50}
                            checkFileSizeMsg="文件大小不能超过50MB"
                            sysCode="OA"
                            businessCode="Taskinfo"
                            categoryCode="taskReEstimationFile"
                            checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                            BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                            RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                            checkFileTypeMsg="附件格式不合规，请确认！"
                        >
                            <Button className={styles.attachFile} type="link" disabled={disabled}>
                                添加附件
                            </Button>
                        </FileUpload>
                    )}
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default Form.create()(ReEstimateActionModal);
